/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GerenciarSalas.java
 *
 * Created on Jul 17, 2011, 9:58:53 PM
 */

package janelas;

import classes.Equipamento;
import classes.Sala;
import db.EquipDAO;
import db.LocalDAO;
import db.ReservaDAO;
import db.SalaDAO;
import java.awt.Component;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import projetofinaltecnicas.Main;

/**
 * 
 * @author Matheus Freire
 */

public class GerenciarSalas extends javax.swing.JPanel {

    int idSala;

    String idioma;
    String usuario;
    String[] tabela = new String[4];
    String[] eqp = new String[2];
    String frase;

    /** Creates new form GerenciarSalas */
    public GerenciarSalas(String idioma, String usuario) {
        initComponents();

        this.idioma = idioma;
        this.usuario = usuario;
        
        internacionaliza();
        organizarHeaderSalas();
        organizarHeaderEquip();
        
        jiduser.setText(usuario);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popsala = new javax.swing.JPopupMenu();
        inserirSala = new javax.swing.JMenuItem();
        editarSala = new javax.swing.JMenuItem();
        removerSala = new javax.swing.JMenuItem();
        equip = new javax.swing.JMenuItem();
        jScrollPane3 = new javax.swing.JScrollPane();
        tabelasala = new javax.swing.JTable();
        titulo = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        juser = new javax.swing.JLabel();
        jiduser = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jRemover = new javax.swing.JButton();
        jEditar = new javax.swing.JButton();
        jInserir = new javax.swing.JButton();
        jLocal = new javax.swing.JLabel();
        jTipo = new javax.swing.JLabel();
        local = new javax.swing.JComboBox();
        tipo = new javax.swing.JComboBox();
        jLugares = new javax.swing.JLabel();
        lugares = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        idsala = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabelaequip = new javax.swing.JTable();
        jScrollPane4 = new javax.swing.JScrollPane();
        tabelaequip1 = new javax.swing.JTable();
        jSalaLabelD = new javax.swing.JLabel();
        jSalaLabel = new javax.swing.JLabel();
        adicionar = new javax.swing.JButton();
        remover = new javax.swing.JButton();

        inserirSala.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/pencil_add.png"))); // NOI18N
        inserirSala.setText("Inserir");
        inserirSala.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inserirSalaActionPerformed(evt);
            }
        });
        popsala.add(inserirSala);

        editarSala.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/pencil.png"))); // NOI18N
        editarSala.setText("Editar");
        editarSala.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editarSalaActionPerformed(evt);
            }
        });
        popsala.add(editarSala);

        removerSala.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/delete.png"))); // NOI18N
        removerSala.setText("Remover");
        removerSala.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removerSalaActionPerformed(evt);
            }
        });
        popsala.add(removerSala);

        equip.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/monitor.png"))); // NOI18N
        equip.setText("Equipamentos");
        equip.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                equipActionPerformed(evt);
            }
        });
        popsala.add(equip);

        setMinimumSize(new java.awt.Dimension(776, 552));
        setSize(new java.awt.Dimension(776, 552));
        addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                formComponentAdded(evt);
            }
        });

        tabelasala.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "N Lugares", "Local", "TIpo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelasala.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabelasala.setShowGrid(true);
        tabelasala.setShowHorizontalLines(false);
        tabelasala.getTableHeader().setReorderingAllowed(false);
        tabelasala.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelasalaMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tabelasala);

        titulo.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        titulo.setText("Gerenciar Sala");

        juser.setFont(new java.awt.Font("Lucida Grande", 1, 13));
        juser.setText("Usuário");

        jiduser.setText("ID User");

        jRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/delete.png"))); // NOI18N
        jRemover.setText("Remover");
        jRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRemoverActionPerformed(evt);
            }
        });

        jEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/pencil.png"))); // NOI18N
        jEditar.setText("Editar");
        jEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jEditarActionPerformed(evt);
            }
        });

        jInserir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/pencil_add.png"))); // NOI18N
        jInserir.setText("Inserir");
        jInserir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jInserirActionPerformed(evt);
            }
        });

        jLocal.setText("Local");

        jTipo.setText("Tipo");

        local.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        tipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Aula", "Reunião", "Auditório" }));

        jLugares.setText("Quantidade de Lugares");

        jLabel5.setText("ID");

        tabelaequip.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID Equipamento", "Nome"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaequip.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabelaequip.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tabelaequip);
        tabelaequip.getColumnModel().getColumn(0).setResizable(false);
        tabelaequip.getColumnModel().getColumn(1).setResizable(false);

        tabelaequip1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID Equipamento", "Nome"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaequip1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabelaequip1.getTableHeader().setReorderingAllowed(false);
        jScrollPane4.setViewportView(tabelaequip1);
        tabelaequip1.getColumnModel().getColumn(0).setResizable(false);
        tabelaequip1.getColumnModel().getColumn(1).setResizable(false);

        jSalaLabelD.setText("Equipamentos Disponiveis");

        jSalaLabel.setText("Equipamentos na Sala");

        adicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/arrow_right.png"))); // NOI18N
        adicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                adicionarActionPerformed(evt);
            }
        });

        remover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/arrow_left.png"))); // NOI18N
        remover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removerActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 736, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(jSeparator2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 736, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(24, 24, 24)
                        .add(jLabel5)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(idsala, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 71, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(66, 66, 66)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLugares)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(lugares, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 71, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLocal)
                                    .add(jTipo))
                                .add(26, 26, 26)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                    .add(local, 0, 166, Short.MAX_VALUE)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, tipo, 0, 166, Short.MAX_VALUE))))
                        .add(160, 160, 160)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jRemover, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
                            .add(jInserir, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jEditar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .add(53, 53, 53))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 736, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(titulo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 209, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 253, Short.MAX_VALUE)
                                .add(juser)
                                .add(18, 18, 18)
                                .add(jiduser)
                                .add(158, 158, 158)))
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 266, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 77, Short.MAX_VALUE)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(adicionar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 64, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(remover, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 64, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(63, 63, 63))
                            .add(layout.createSequentialGroup()
                                .add(jSalaLabelD)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jSalaLabel)
                            .add(jScrollPane4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 266, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(titulo)
                    .add(juser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jiduser))
                .add(8, 8, 8)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                .add(jLabel5)
                                .add(idsala, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createSequentialGroup()
                                .add(1, 1, 1)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                    .add(jLocal)
                                    .add(local, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                    .add(jTipo)
                                    .add(tipo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                    .add(jLugares)
                                    .add(lugares, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                        .add(4, 4, 4))
                    .add(layout.createSequentialGroup()
                        .add(jInserir)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jEditar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jRemover)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)))
                .add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 187, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(32, 32, 32)
                        .add(adicionar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 43, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(remover, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 43, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jSalaLabel)
                            .add(jSalaLabelD, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(4, 4, 4)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jScrollPane4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 114, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 110, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(29, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tabelasalaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelasalaMouseClicked
        // TODO add your handling code here:
        int linha=0;
        int coluna=0;

        linha = tabelasala.getSelectedRow();

        if(evt.getButton() == java.awt.event.MouseEvent.BUTTON1 && evt.getClickCount() == 2){
            popsala.show(tabelasala, evt.getX() , evt.getY());
            idSala = Integer.parseInt(tabelasala.getModel().getValueAt(linha, coluna).toString());
        }else{
            idSala = Integer.parseInt(tabelasala.getModel().getValueAt(linha, coluna).toString());
        }
}//GEN-LAST:event_tabelasalaMouseClicked

    private void jRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRemoverActionPerformed
        // TODO add your handling code here:
        int idS = Integer.parseInt(idsala.getText());
        
        int j;

        if(idioma.equals("en_US")){
            Object[] options = {"Yes","No"};
            j = JOptionPane.showOptionDialog(null,
                            "Do you really want to remove this classroom?\nAll data associated with this clasrrom will be lost.",
                            "Edit Equipment",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            null,
                            options,
                            options[1]);
        }
        else{
            Object[] options = {"Sim","Não"};
            j = JOptionPane.showOptionDialog(null,
                            "Deseja realmente remover está sala?\nTodas as informações associadas a ela serão perdidas.",
                            "Editar Equipamento",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            null,
                            options,
                            options[1]);
            }
        if (j==JOptionPane.YES_OPTION){
            try{
                SalaDAO saladao = new SalaDAO();
                ReservaDAO resdao = new ReservaDAO();
                EquipDAO equipd = new EquipDAO();
                List<Sala> lista;
                List<Equipamento> lista1 = new ArrayList<Equipamento>();
                List<Equipamento> lista2;

                int ids[] = equipd.idsEquip(idS);

                for(int i=0;i<ids.length;i++){
                    equipd.removerEquipSala(ids[i]);
                    equipd.editarEquipStatus1(ids[i]);
                }

                saladao.removerSala(idS);
                resdao.removerSolicSala(idS);

                lista = saladao.salaListar();
                lista2 = equipd.equipListarDispo();

                preencherTabela(lista);
                preencherEquipSala(lista1);
                preencherEquipDisponivel(lista2);

                idsala.setText("-");
                tipo.setSelectedIndex(0);
                local.setSelectedIndex(0);
                lugares.setText("");
                jRemover.setEnabled(false);
                jInserir.setEnabled(true);
                local.setEnabled(true);
                tipo.setEnabled(true);
                lugares.setEditable(true);
                Main.log.info("O usuario: "+usuario+", removeu com sucesso a sala: "+idS);
            }
            catch(SQLException ex){
                ex.printStackTrace();
                Main.log.info("O usuario: "+usuario+", teve problemas e não conseguiui remover a sala: "+idS);
            }
        }
        
}//GEN-LAST:event_jRemoverActionPerformed

    private void jEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jEditarActionPerformed
        // TODO add your handling code here:
        String localN = local.getSelectedItem().toString();
        String tipoN = tipo.getSelectedItem().toString();
        int idS = Integer.parseInt(idsala.getText());
        String lugar = lugares.getText();

        if(verificarLugares(lugar)==1){
            Main.log.info("O usuario: "+usuario+", inseriu valores invalidos.");
            if(idioma.equals("en_US")){
                JOptionPane.showMessageDialog(null, "All fields must be filled and with correct values!", "ERROR!", JOptionPane.ERROR_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(null, "Todos os campos devem ser preenchidos e com valores corretos!", "ERRO!", JOptionPane.ERROR_MESSAGE);
            }
        }else{
            int lugaresN = Integer.parseInt(lugares.getText());

            int j;

            if(idioma.equals("en_US")){
                Object[] options = {"Yes","No"};
                j = JOptionPane.showOptionDialog(null,
                                "Do you really want to edit this classroom?",
                                "Edit Equipment",
                                JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE,
                                null,
                                options,
                                options[1]);
            }
            else{
                Object[] options = {"Sim","Não"};
                j = JOptionPane.showOptionDialog(null,
                                "Deseja realmente editar está sala?",
                                "Editar Equipamento",
                                JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE,
                                null,
                                options,
                                options[1]);
                }
            if (j==JOptionPane.YES_OPTION){
                try{
                    SalaDAO saladao = new SalaDAO();
                    Sala sala = new Sala();
                    List<Sala> lista;

                    sala.setIdsala(idS);
                    sala.setLocalsala(localN);
                    sala.setTiposala(tipoN);
                    sala.setQtdlugares(lugaresN);

                    saladao.editarSala(sala);

                    lista = saladao.salaListar();

                    preencherTabela(lista);
                    Main.log.info("O usuario: "+usuario+", editou com sucesso a sala: "+idS);
                }
                catch(SQLException ex){
                    ex.printStackTrace();
                    Main.log.info("O usuario: "+usuario+", teve problema e não conseguiu editar a sala: "+idS);
                }
             }
            }
}//GEN-LAST:event_jEditarActionPerformed

    private void jInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jInserirActionPerformed
        // TODO add your handling code here:

        String localS = local.getSelectedItem().toString();
        String tipoS = tipo.getSelectedItem().toString();
        String lugar = lugares.getText();

        Sala sala = new Sala();

        if(verificarLugares(lugar)==1){
            Main.log.info("O usuario: "+usuario+", inseriu valores invalidos.");
            if(idioma.equals("en_US")){
                JOptionPane.showMessageDialog(null, "All fields must be filled and with correct values!", "ERROR!", JOptionPane.ERROR_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(null, "Todos os campos devem ser preenchidos e com valores corretos!", "ERRO!", JOptionPane.ERROR_MESSAGE);
            }
        }else{
            int qtdlugares = Integer.parseInt(lugares.getText());

            int j;

            if(idioma.equals("en_US")){
                Object[] options = {"Yes","No"};
                j = JOptionPane.showOptionDialog(null,
                                "Do you really want to insert this classroom?",
                                "Edit Equipment",
                                JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE,
                                null,
                                options,
                                options[1]);
            }
            else{
                Object[] options = {"Sim","Não"};
                j = JOptionPane.showOptionDialog(null,
                                "Deseja realmente inserir esta sala?",
                                "Editar Equipamento",
                                JOptionPane.YES_NO_OPTION,
                                JOptionPane.QUESTION_MESSAGE,
                                null,
                                options,
                                options[1]);
                }
            if (j==JOptionPane.YES_OPTION){
                try{
                    SalaDAO saladao = new SalaDAO();
                    List<Sala> lista;

                    sala.setQtdlugares(qtdlugares);
                    sala.setLocalsala(localS);
                    sala.setTiposala(tipoS);

                    saladao.inserirSala(sala);
                    lista = saladao.salaListar();

                    preencherTabela(lista);
                    Main.log.info("O usuario: "+usuario+", inseriu com sucesso uma nova sala.");
                }
                catch(SQLException ex){
                    ex.printStackTrace();
                    Main.log.info("O usuario: "+usuario+", teve problemas e não conseguiu inserir uma nova sala.");
                }
            }
        }
}//GEN-LAST:event_jInserirActionPerformed

    private void formComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_formComponentAdded
        // TODO add your handling code here:
        String[] combolocal;

        idsala.setEditable(false);
        idsala.setText("-");
        jEditar.setEnabled(false);
        jRemover.setEnabled(false);
        adicionar.setEnabled(false);
        remover.setEnabled(false);
        tabelaequip.setEnabled(false);
        tabelaequip1.setEnabled(false);

        tabelaequip.getColumnModel().getColumn(0).setPreferredWidth(20);
        tabelaequip.getColumnModel().getColumn(1).setPreferredWidth(80);

        tabelaequip1.getColumnModel().getColumn(0).setPreferredWidth(20);
        tabelaequip1.getColumnModel().getColumn(1).setPreferredWidth(80);
        
        try{
            SalaDAO sala = new SalaDAO();
            LocalDAO localx = new LocalDAO();

            combolocal = localx.comboLocal();

            local.setModel(new javax.swing.DefaultComboBoxModel(combolocal));
        }
        catch(SQLException ex){
            ex.printStackTrace();
        }

        List<Sala> lista;

        try{
            List<Equipamento> lista1;
            EquipDAO equipd = new EquipDAO();

            lista1 = equipd.equipListarDispo();

            preencherEquipDisponivel(lista1);
            SalaDAO saladao = new SalaDAO();

            lista = saladao.salaListar();

            preencherTabela(lista);
        }
        catch(SQLException ex){
            ex.printStackTrace();
        }
    }//GEN-LAST:event_formComponentAdded

    private void inserirSalaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inserirSalaActionPerformed
        // TODO add your handling code here:

        jInserir.setEnabled(true);
        jEditar.setEnabled(false);
        jRemover.setEnabled(false);
        adicionar.setEnabled(false);
        remover.setEnabled(false);
        tabelaequip.setEnabled(false);
        tabelaequip1.setEnabled(false);
        local.setEnabled(true);
        tipo.setEnabled(true);
        lugares.setEditable(true);

        idsala.setText("-");
        tipo.setSelectedItem(0);
        local.setSelectedIndex(0);
        lugares.setText("");

        try{
            List<Equipamento> lista1;
            EquipDAO equipd = new EquipDAO();

            lista1 = equipd.equipListarDispo();

            preencherEquipDisponivel(lista1);
            
            List<Equipamento> lista = new ArrayList<Equipamento>();
            preencherEquipSala(lista);

            jSalaLabel.setText(frase);
        }
        catch(SQLException ex){
            ex.printStackTrace();
        }

    }//GEN-LAST:event_inserirSalaActionPerformed

    private void equipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_equipActionPerformed
        // TODO add your handling code here:

        jInserir.setEnabled(false);
        jEditar.setEnabled(false);
        jRemover.setEnabled(false);
        adicionar.setEnabled(true);
        remover.setEnabled(true);
        tabelaequip.setEnabled(true);
        tabelaequip1.setEnabled(true);
        local.setEnabled(false);
        tipo.setEnabled(false);
        lugares.setEditable(false);

        int ids[];

        try{
            SalaDAO salad = new SalaDAO();
            Sala sala = new Sala();

            sala = salad.sala(idSala);

            idsala.setText(""+sala.getIdsala());
            tipo.setSelectedItem(sala.getTiposala());
            local.setSelectedItem(sala.getLocalsala());
            lugares.setText(""+sala.getQtdlugares());

        }catch(SQLException e){
            e.printStackTrace();
        }
        
        try{
            List<Equipamento> lista;
            List<Equipamento> lista1 = new ArrayList<Equipamento>();
            EquipDAO equipd = new EquipDAO();

            lista = equipd.equipListarDispo();

            preencherEquipDisponivel(lista);

            int idS = Integer.parseInt(idsala.getText());
            ids = equipd.idsEquip(idS);

            for(int i=0;i<ids.length;i++){
                lista1.add(equipd.equipSala(ids[i]));
            }

            preencherEquipSala(lista1);

            jSalaLabel.setText(frase+idS);
        }catch(SQLException e){
            e.printStackTrace();
        }
    }//GEN-LAST:event_equipActionPerformed

    private void adicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adicionarActionPerformed
        // TODO add your handling code here:
        int lin = tabelaequip.getSelectedRow();
        int col = tabelaequip.getSelectedColumn();

        if(lin<0 || col<0){
            System.out.println("erro");
        }else{
            int idEquip = Integer.parseInt(tabelaequip.getValueAt(lin, 0).toString());

            try{
                EquipDAO equipd = new EquipDAO();
                int ids[];
                int idS = Integer.parseInt(idsala.getText());
                List<Equipamento> lista1 = new ArrayList<Equipamento>();

                equipd.editarEquipStatus(idEquip);
                equipd.inserirEquipamentoSala(idS, idEquip);

                ids = equipd.idsEquip(idS);

                for(int i=0;i<ids.length;i++){
                    lista1.add(equipd.equipSala(ids[i]));
                }

                preencherEquipSala(lista1);

                List<Equipamento> lista;
                
                lista = equipd.equipListarDispo();

                preencherEquipDisponivel(lista);
            }catch(SQLException e){
                e.printStackTrace();
            }
        }

    }//GEN-LAST:event_adicionarActionPerformed

    private void removerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removerActionPerformed
        // TODO add your handling code here:

        int lin = tabelaequip1.getSelectedRow();
        int col = tabelaequip1.getSelectedColumn();

        if(lin<0 || col<0){
            System.out.println("erro");
        }else{
            int idEquip = Integer.parseInt(tabelaequip1.getValueAt(lin, 0).toString());

            try{
                EquipDAO equipd = new EquipDAO();
                int ids[];
                int idS = Integer.parseInt(idsala.getText());
                List<Equipamento> lista;
                List<Equipamento> lista1 = new ArrayList<Equipamento>();

                equipd.editarEquipStatus1(idEquip);
                equipd.removerEquipSala(idEquip);

                lista = equipd.equipListarDispo();
                
                preencherEquipDisponivel(lista);

                ids = equipd.idsEquip(idS);

                for(int i=0;i<ids.length;i++){
                    lista1.add(equipd.equipSala(ids[i]));
                }

                preencherEquipSala(lista1);
                jSalaLabel.setText(frase+idS);
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_removerActionPerformed

    private void editarSalaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarSalaActionPerformed
        // TODO add your handling code here:
        jInserir.setEnabled(false);
        jEditar.setEnabled(true);
        jRemover.setEnabled(false);
        adicionar.setEnabled(false);
        remover.setEnabled(false);
        tabelaequip.setEnabled(false);
        tabelaequip1.setEnabled(false);
        local.setEnabled(true);
        tipo.setEnabled(true);
        lugares.setEditable(true);
        
        try{
            SalaDAO salad = new SalaDAO();
            Sala sala = new Sala();

            sala = salad.sala(idSala);

            idsala.setText(""+sala.getIdsala());
            tipo.setSelectedItem(sala.getTiposala());
            local.setSelectedItem(sala.getLocalsala());
            lugares.setText(""+sala.getQtdlugares());

            int idS = Integer.parseInt(idsala.getText());

            jSalaLabel.setText(frase+idS);
        }catch(SQLException e){
            e.printStackTrace();
        }
    }//GEN-LAST:event_editarSalaActionPerformed

    private void removerSalaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removerSalaActionPerformed
        // TODO add your handling code here:
        jInserir.setEnabled(false);
        jEditar.setEnabled(false);
        jRemover.setEnabled(true);
        adicionar.setEnabled(false);
        remover.setEnabled(false);
        tabelaequip.setEnabled(false);
        tabelaequip1.setEnabled(false);
        local.setEnabled(false);
        tipo.setEnabled(false);
        lugares.setEditable(false);

        try{
            SalaDAO salad = new SalaDAO();
            EquipDAO equipd = new EquipDAO();
            Sala sala = new Sala();

            sala = salad.sala(idSala);

            idsala.setText(""+sala.getIdsala());
            tipo.setSelectedItem(sala.getTiposala());
            local.setSelectedItem(sala.getLocalsala());
            lugares.setText(""+sala.getQtdlugares());

            List<Equipamento> lista1 = new ArrayList<Equipamento>();
            int idS = Integer.parseInt(idsala.getText());
            int ids[] = equipd.idsEquip(idS);

            for(int i=0;i<ids.length;i++){
                lista1.add(equipd.equipSala(ids[i]));
            }

            preencherEquipSala(lista1);
            jSalaLabel.setText(frase+idS);
        }catch(SQLException e){
            e.printStackTrace();
        }
    }//GEN-LAST:event_removerSalaActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton adicionar;
    private javax.swing.JMenuItem editarSala;
    private javax.swing.JMenuItem equip;
    private javax.swing.JTextField idsala;
    private javax.swing.JMenuItem inserirSala;
    private javax.swing.JButton jEditar;
    private javax.swing.JButton jInserir;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLocal;
    private javax.swing.JLabel jLugares;
    private javax.swing.JButton jRemover;
    private javax.swing.JLabel jSalaLabel;
    private javax.swing.JLabel jSalaLabelD;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel jTipo;
    private javax.swing.JLabel jiduser;
    private javax.swing.JLabel juser;
    private javax.swing.JComboBox local;
    private javax.swing.JTextField lugares;
    private javax.swing.JPopupMenu popsala;
    private javax.swing.JButton remover;
    private javax.swing.JMenuItem removerSala;
    private javax.swing.JTable tabelaequip;
    private javax.swing.JTable tabelaequip1;
    private javax.swing.JTable tabelasala;
    private javax.swing.JComboBox tipo;
    private javax.swing.JLabel titulo;
    // End of variables declaration//GEN-END:variables
    
    public void preencherTabela(List<Sala> listasala){

        DefaultTableModel tabela = (DefaultTableModel) tabelasala.getModel();

        while (tabela.getRowCount() > 0) { //vai pegar todas as linha selecionadas maiores que zero, é vai remove-las!
            tabela.removeRow(0);
        }

        String[] linha = new String[]{null, null, null, null}; //colocando null em todas as colunas
        for (int i = 0; i < listasala.size(); i++) {
            tabela.addRow(linha);
            tabela.setValueAt(listasala.get(i).getIdsala(), i, 0);
            tabela.setValueAt(listasala.get(i).getQtdlugares(), i, 1);
            tabela.setValueAt(listasala.get(i).getLocalsala(), i, 2);
            tabela.setValueAt(listasala.get(i).getTiposala(), i, 3);
        }


    }

    public void preencherEquipDisponivel(List<Equipamento> lista){
        DefaultTableModel tabela = (DefaultTableModel) tabelaequip.getModel();

        while (tabela.getRowCount() > 0) { //vai pegar todas as linha selecionadas maiores que zero, é vai remove-las!
            tabela.removeRow(0);
        }

        String[] linha = new String[]{null, null}; //colocando null em todas as colunas
        for (int i = 0; i < lista.size(); i++) {
            tabela.addRow(linha);
            tabela.setValueAt(lista.get(i).getIdequip(), i, 0);
            tabela.setValueAt(lista.get(i).getNome(), i, 1);
        }

        descricao(lista);
    }

    public void preencherEquipSala(List<Equipamento> lista){
        DefaultTableModel tabela = (DefaultTableModel) tabelaequip1.getModel();

        while (tabela.getRowCount() > 0) { //vai pegar todas as linha selecionadas maiores que zero, é vai remove-las!
            tabela.removeRow(0);
        }

        String[] linha = new String[]{null, null}; //colocando null em todas as colunas
        for (int i = 0; i < lista.size(); i++) {
            tabela.addRow(linha);
            tabela.setValueAt(lista.get(i).getIdequip(), i, 0);
            tabela.setValueAt(lista.get(i).getNome(), i, 1);
        }

        descricao1(lista);
    }

    public void organizarHeaderSalas(){

        DefaultTableModel model = (DefaultTableModel) tabelasala.getModel();
        JTable table = new JTable(model);

        for(int i=0;i<4;i++){
            tabelasala.getTableHeader().setFont(new java.awt.Font(""+tabela[i],java.awt.Font.PLAIN, 11));
            tabelasala.getColumnModel().getColumn(i).setHeaderValue(""+tabela[i]);
        }
    }

    public void internacionaliza(){
        ResourceBundle palavras = ResourceBundle.getBundle("idiomas.Lingua_"+idioma);

        tabela[0] = palavras.getString("salasHeader.id");
        tabela[1] = palavras.getString("salasHeader.lugares");
        tabela[2] = palavras.getString("salasHeader.local");
        tabela[3] = palavras.getString("salasHeader.tipo");

        eqp[0] = palavras.getString("sequipHeader.id");
        eqp[1] = palavras.getString("sequipHeader.nome");

        jInserir.setText(palavras.getString("gerenciarEquip.inserir"));
        jEditar.setText(palavras.getString("gerenciarEquip.editar"));
        jRemover.setText(palavras.getString("gerenciarEquip.remover"));
        juser.setText(palavras.getString("verificar.user"));
        inserirSala.setText(palavras.getString("gerenciarEquip.inserir"));
        editarSala.setText(palavras.getString("gerenciarEquip.editar"));
        removerSala.setText(palavras.getString("gerenciarEquip.remover"));
        equip.setText(palavras.getString("gerenciarS.equip"));

        titulo.setText(palavras.getString("gerenciarS.titulo"));
        jLugares.setText(palavras.getString("gerenciarS.lugares"));
        jTipo.setText(palavras.getString("gerenciarS.tipo"));
        jLocal.setText(palavras.getString("gerenciarS.local"));
        jSalaLabel.setText(palavras.getString("gerenciarS.salad"));
        jSalaLabelD.setText(palavras.getString("gerenciarS.sala"));
        frase = palavras.getString("gerenciarS.salad");
    }

    public void descricao(final List<Equipamento> lista){
        tabelaequip.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected,
                        hasFocus, row, column);

                setToolTipText(lista.get(row).getDescricao());

                return this;
            }
        });
    }

    public void descricao1(final List<Equipamento> lista){
        tabelaequip1.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected,
                        hasFocus, row, column);

                setToolTipText(lista.get(row).getDescricao());

                return this;
            }
        });
    }

    public void organizarHeaderEquip(){
        for(int i=0;i<2;i++){
            tabelaequip.getTableHeader().setFont(new java.awt.Font(""+eqp[i],java.awt.Font.PLAIN, 11));
            tabelaequip.getColumnModel().getColumn(i).setHeaderValue(""+eqp[i]);
        }

        for(int i=0;i<2;i++){
            tabelaequip1.getTableHeader().setFont(new java.awt.Font(""+eqp[i],java.awt.Font.PLAIN, 11));
            tabelaequip1.getColumnModel().getColumn(i).setHeaderValue(""+eqp[i]);
        }
    }

    public int verificarLugares(String lugares){

          Pattern p = Pattern.compile("[0123456789]{1,4}");

          Matcher m = p.matcher(lugares);

          boolean matchFound = m.matches();

          if (matchFound){
              return 0;
          }else{
              return 1;
          }
    }
}
